package com.zy.vue_back.controller;

import com.zy.vue_back.dto.LoginResponse;
import com.zy.vue_back.entity.User;
import com.zy.vue_back.utils.JwtTokenUtil;
import com.zy.vue_back.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

@RequestMapping("/user")
@RestController
@CrossOrigin
@Slf4j
public class UserController {
    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.expiration}")
    private Long expiration;

    @PostMapping("/login")
    public Result login(@RequestBody User user)
    {
        if (user == null) {
            return Result.error(401, "用户名或密码错误");
        }
        log.info("user={}", user);
        // 2. 生成Token
        String token = jwtTokenUtil.generateToken(user.getUserName(), user.getUserId());

        // 4. 构建响应
        LoginResponse loginResponse = new LoginResponse(
                token,
                expiration, // 从配置获取过期时间
                user
        );
        return Result.success( "登录成功", loginResponse);
    }

    @GetMapping("/info")
    public Result info(@RequestParam String token)
    {
        if (token == null) {
            return Result.error(403, "token is null");
        }
        log.info("token:{}", token);
        String username = jwtTokenUtil.getUsernameFromToken(token);
        log.info("username:{}", username);
        User user = new User();
        user.setUserName(username);
        user.setAvatar("https://picsum.photos/100/100");
        user.setEmail("201646223**@qq.com");
        return Result.success(user);
    }
}
